package repositories

import (
	"github.com/jinzhu/gorm"
	"github.com/sirupsen/logrus"
	"micro-member/datamodels"
	"micro-member/initialize"
	"time"
)

type RewardRecordInterface interface {
	SelectInfo(id int64) (datamodels.RewardRecord, error) 	        //查询记录信息
	Update(id int64, uid int64, rewardNum int64) (int64, error) 	//更新记录信息
}

//	返回结构体对象
func NewRewardRecordInterface() RewardRecordInterface {
	return &rewardRecord{}
}

//  结构体
type rewardRecord struct {
}

//查询记录信息
func (this *rewardRecord) SelectInfo(id int64) (datamodels.RewardRecord, error) {
	var recordInfo datamodels.RewardRecord
	//读取数据库
	if err := initialize.MsqlDb.Where("id = ? ", id).Find(&recordInfo).Error; err != nil {
		logrus.Infof("[获取记录信息失败]-[%s]", err.Error())
		return recordInfo, err
	}
	return recordInfo, nil
}

//更新记录信息
func (this *rewardRecord) Update(id int64, uid int64, rewardNum int64) (int64,error) {
	var record datamodels.RewardRecord
	var user datamodels.User
	//事务开始
	tx := initialize.MsqlDb.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		logrus.Infof("Record:Update:",err)
		return 0, err
	}
	if err := tx.Model(&record).Debug().Where("id = ? and status = ?", id, 0).Updates(map[string]interface{}{"status": 1, "update_time": time.Now().Unix()}).Error; err != nil {
		tx.Rollback()
		logrus.Infof("[更新记录失败]-[%s]", err.Error())
		return 0,err
	}

	if err := tx.Model(&user).Where("id = ?", uid).Updates(map[string]interface{}{"reward": gorm.Expr("reward + ?", rewardNum), "update_time": time.Now().Unix()}).Error; err != nil {
		tx.Rollback()
		logrus.Infof("[更新用户信息失败]-[%s]", err.Error())
		return 0,err
	}

	return uid, tx.Commit().Error
}